package cn.tedu.lucky.draw.server.service.impl;

import cn.tedu.lucky.draw.server.common.enums.DrawEnum;
import cn.tedu.lucky.draw.server.protocol.po.ActivityPrize;
import cn.tedu.lucky.draw.server.protocol.po.Prize;
import cn.tedu.lucky.draw.server.protocol.query.PrizeQuery;
import cn.tedu.lucky.draw.server.repository.ActivityPrizeRepository;
import cn.tedu.lucky.draw.server.repository.PrizeRepostiory;
import cn.tedu.lucky.draw.server.service.IPrizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PrizeServiceImpl implements IPrizeService {

    List<Prize> prizeList;

    @Autowired
    private PrizeRepostiory prizeRepostiory;

    @Autowired
    private ActivityPrizeRepository activityPrizeRepository;

    @Override
    public List<Prize> findAll(PrizeQuery prizeQuery) {

        if (prizeList==null){
            //当前集合中没有数据
            prizeList = prizeRepostiory.findAll();
        }

        String name = prizeQuery.getName();

        Integer status = prizeQuery.getStatus();

        return prizeList.stream().filter( prize -> (name ==null ||  name.equals(prize.getName()) || name ==""))
                .filter(prize -> ( status==null || status.equals(prize.getStatus()) )).collect(Collectors.toList());
    }

    @Override
    public void save(Prize prize) {
        LocalDateTime now = LocalDateTime.now();
        prize.setCreateTime(now);
        prize.setUpdateTime(now);
        prizeRepostiory.save(prize);
        prizeList=null;

    }

    @Override
    public List<Prize> findPrizesByActivityId(Long id) {
        //查询该活动下绑定所有的奖品ID
        List<ActivityPrize> activityPrizes = activityPrizeRepository.findByActivityId(id);
        List<Long> prizeIds = activityPrizes.stream().map(ActivityPrize::getPrizeId).collect(Collectors.toList());
        List<Prize> prizes = prizeRepostiory.findAllById(prizeIds);
        return prizes;
    }

    @Override
    public List<Prize> findNoBindPrize(Long id) {
        //1.获取当前活动已绑定的奖品ID
        List<ActivityPrize> activityPrizes = activityPrizeRepository.findByActivityId(id);
        ArrayList<Long> ids = new ArrayList<>();
        for (ActivityPrize activityPrize : activityPrizes) {
            ids.add(activityPrize.getPrizeId());
        }
        //2.查询未绑定的奖品
        Integer status= Integer.valueOf(DrawEnum.ENABLE.getCode());
        if (ids.size() == 0 || ids.isEmpty()){
            //获取已启用的奖品
            return prizeRepostiory.findByStatusEquals(status);
        }
        //查询不在ids当中的已启用的奖品
        return prizeRepostiory.findByIdNotInAndStatusEquals(ids,status);
    }
    /**
     * 返回一个User对象  user;
     * 返回一个User对象 Mono<User>
     *
     * Flux
     * 返回0到N个对象
     * List<User>
     * Flux<User>
     */
}
